<template>
  <!-- 充放电曲线 -->
  <div class="chartContent">
    <a-form
      :model="form"
      :rules="rules"
      layout="inline"
      :labelCol="labelCol"
      ref="formRef"
      class="chartForm"
    >
      <a-form-item label="显示维度" name="name">
        <a-select
          ref="select"
          v-model:value="chartType"
          class="formSelect"
          placeholder="请选择"
          style="width: 120px"
        >
          <a-select-option
            v-for="item in chartTypeList"
            :value="item.value"
            :key="item.value"
          >
            {{ item.label }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="日期" name="code">
        <a-date-picker
          v-model:value="form.date1"
          placeholder="选择日期"
          class="formSelect"
          formatter="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          :allowClear="false"
        />
        <a-date-picker
          v-model:value="form.date2"
          placeholder="选择日期"
          class="formSelect"
          formatter="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          :allowClear="false"
        />
      </a-form-item>
      <a-button
        type="primary"
        class="filterBtn"
        @click="getDischargChartData"
        :loading="chartLoading"
        >查询</a-button
      >
      <a-button v-hasPermission="'monitorChargeDischargeCheckData'" type="primary" class="filterBtn yellowBtn" @click="checkData"
        >查看数据</a-button
      >
    </a-form>

    <a-spin :spinning="chartLoading">
      <div
        v-for="(chartData, index) in chartsData"
        :key="index"
        :id="`chargeDischargechart${index}`"
        class="chartContainer"
      />
      <a-empty
        v-if="!chartsData?.length"
        style="opacity: 0.5; margin-top: 50px"
      />
    </a-spin>
  </div>

  <!-- 查看数据 -->
  <DetailsData
    :detailsDataVisible="detailsDataVisible"
    :chartsTableData="chartsTableData"
    :chartType="chartType"
    @update:detailsDataVisible="(val) => (detailsDataVisible = val)"
  />
</template>
<script setup>
import DetailsData from "./detailsData.vue"
import * as echarts from "echarts"
import { chartOption } from "./chartOption"
import { getCurrentDate, getYesterdayDateFormatted } from "@/utils/common"
import { cloneDeep } from "lodash-es"

import { random } from "lodash-es"
const props = defineProps({
  stationInfo: {
    type: Number,
  },
})
const $api = inject("$api")
const detailsDataVisible = ref(false)
const form = ref({
  date1: null,
  date2: null,
})
const chartType = ref(null)

const chartTypeList = ref([
  {
    value: 1,
    label: "电池簇",
  },
  {
    value: 2,
    label: "电池堆",
  },
  {
    value: 3,
    label: "电站",
  },
])

const chartsTableData = ref([])
const chartOptionData = ref()
const chartLoading = ref(false)
const chartsData = ref([
  {
    name: "充放曲线1",
    data: [],
  },
  {
    name: "充放曲线2",
    data: [],
  },
])
const checkData = () => {
  detailsDataVisible.value = true
}
const getDischargeDimension = async () => {
  const res = await $api.dischargeDimension({
    stationId: props.stationInfo.id,
  })
  if (res?.code === 0) {
    chartTypeList.value = chartTypeList.value.filter((item) =>
      res.data.includes(item.value)
    )
    chartType.value = chartTypeList.value[0].value
    getDischargChartData()
  }
}
const powerChart = ref([])
const initChart = (chartData, index, date, dateIndex) => {
  const xAxisData = chartData.lineData.map(
    (item) => item.dateTime.split(" ")[1]
  )
  powerChart.value[index].series[dateIndex].data = chartData.lineData
  powerChart.value[index].series[dateIndex].name = `${date}充放曲线`
  powerChart.value[index].xAxis.data = xAxisData
  let name = ""
  if (chartType.value === 1) {
    // 选了电池簇，显示linkName + blockName
    name = `${chartData.linkName}-${chartData.blockName}`
  }
  if (chartType.value === 2) {
    // 选了电池堆，显示linkName
    name = `${chartData.linkName}`
  }
  powerChart.value[index].title.text = name
}

const getLineData = async (date, dateIndex) => {
  const params = {
    stationId: props.stationInfo.id,
    dimensionType: chartType.value,
    date,
  }
  const res = await $api.dischargeCurve(params)
  if (res?.data) {
    chartsTableData.value.push(res.data)
    return res.data
  } else {
    return null
  }
}
const getDischargChartData = async () => {
  chartsData.value = []
  chartsTableData.value = []
  chartOptionData.value = cloneDeep(chartOption)
  if (!form.value.date1 || !form.value.date2) {
    message.error("请选择日期")
    return
  }
  const date = [form.value.date1, form.value.date2]
  chartLoading.value = true
  try {
    const promises = date.map((item, dateIndex) => {
      return getLineData(item, dateIndex) // 这里返回 Promise
    })
    await Promise.all(promises).then(async (resList) => {
      chartsData.value = resList[0]
      powerChart.value = chartsData.value.map(() =>
        cloneDeep(chartOptionData.value)
      )
      resList.flatMap((item, index) => {
        return item.map((chartData, chartIndex) => {
          initChart(chartData, chartIndex, chartData.date, index)
          return { chartData, index } // 这里可以保留需要的信息
        })
      })

      await nextTick()
      powerChart.value.forEach((chartOption, index) => {
        const chartEl = document.getElementById("chargeDischargechart" + index)
        if (chartEl) {
          const chartInstance = echarts.init(chartEl)
          chartInstance.resize()
          chartInstance.clear()
          chartInstance.setOption(chartOption)
        }
      })
    })
  } finally {
    chartLoading.value = false // 最后关闭加载状态
  }
}
onMounted(() => {})
const handleChageStation = () => {
  form.value.date1 = getYesterdayDateFormatted()
  form.value.date2 = getCurrentDate()
  getDischargeDimension()
}
defineExpose({ handleChageStation })
</script>

<style lang="less" scoped>
.chartForm {
  margin-top: 20px;
}
.ant-form-item {
  margin-bottom: 20px;
}
.chartContainer {
  margin-bottom: 20px;
  width: 100%;
  height: 420px;
  background: #141414;
  border-radius: 4px;
}
.filterBtn {
  margin-right: 20px;
}
</style>
